package com.flycms.modules.user.service.impl;

import com.flycms.common.pager.Pager;
import com.flycms.common.utils.StringUtils;
import com.flycms.common.utils.mark.SnowFlakeUtils;
import com.flycms.common.utils.result.LayResult;
import com.flycms.common.utils.result.Result;
import com.flycms.common.utils.text.Convert;
import com.flycms.modules.user.dao.AdminMenuDao;
import com.flycms.modules.user.dao.AdminRoleDao;
import com.flycms.modules.user.dao.AdminRoleMenuMergeDao;
import com.flycms.modules.user.dao.AdminRoleMergeDao;
import com.flycms.modules.user.entity.*;
import com.flycms.modules.user.service.AdminRoleService;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * Biz-Boot, All rights reserved
 * 版权：企业之家网 -- 企业建站管理系统<br/>
 * 开发公司：97560.com<br/>
 *
 * 角色 业务层处理
 * 
 * @author 孙开飞
 */
@Service
public class AdminRoleServiceImpl implements AdminRoleService {
    @Autowired
    private AdminRoleDao adminRoleDao;

    @Autowired
    private AdminMenuDao adminMenuDao;

    @Autowired
    private AdminRoleMenuMergeDao adminRoleMenuMergeDao;

    @Autowired
    private AdminRoleMergeDao adminRoleMergeDao;

    // ///////////////////////////////
    // /////       增加       ////////
    // ///////////////////////////////

    /**
     * 新增保存角色信息
     *
     * @param adminRole 角色信息
     * @return 结果
     */
    @Transactional
    public int addAdminRole(AdminRole adminRole)
    {
        adminRole.setId(SnowFlakeUtils.nextId());
        adminRole.setCreateTime(LocalDateTime.now());
        // 新增角色信息
        return adminRoleDao.insertRole(adminRole);
    }

    /**
     * 批量选择授权用户角色
     *
     * @param roleId 角色ID
     * @param userIds 需要删除的用户数据ID
     * @return 结果
     */
    public int insertAuthUsers(Long roleId, String userIds)
    {
        Long[] users = Convert.toLongArray(userIds);
        // 新增用户与角色管理
        List<AdminRoleMerge> list = new ArrayList<AdminRoleMerge>();
        for (Long userId : users)
        {
            AdminRoleMerge ur = new AdminRoleMerge();
            ur.setId(SnowFlakeUtils.nextId());
            ur.setUserId(userId);
            ur.setRoleId(roleId);
            list.add(ur);
        }
        return adminRoleMergeDao.batchUserRole(list);
    }

    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
   public int insertRoleMenu(AdminRole role)
    {
        int rows = 1;
        // 新增用户与角色管理
        List<AdminRoleMenuMerge> list = new ArrayList<AdminRoleMenuMerge>();
        for (Long menuId : role.getMenuIds())
        {
            AdminRoleMenuMerge rm = new AdminRoleMenuMerge();
            rm.setRoleId(role.getId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0)
        {
            rows = adminRoleMenuMergeDao.batchRoleMenu(list);
        }
        return rows;
    }
    // ///////////////////////////////
    // /////        刪除      ////////
    // ///////////////////////////////
    /**
     * 通过角色ID删除角色
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public boolean deleteRoleById(Long roleId)
    {
        return adminRoleDao.deleteRoleById(roleId) > 0 ? true : false;
    }

    /**
     * 批量删除角色信息
     *
     * @param ids 需要删除的数据ID
     * @throws Exception
     */
    @Override
    public Result deleteRoleByIds(String ids){
        Long[] roleIds = Convert.toLongArray(ids);
        for (Long roleId : roleIds)
        {
            AdminRole role = findById(roleId);
            if (countUserRoleByRoleId(roleId) > 0)
            {
                Result.failure(String.format(role.getRoleName()+"%1$s已分配,不能删除"));
            }
        }
        int totalCount=adminRoleDao.deleteRoleByIds(roleIds);
        if(totalCount == 0){
            Result.failure("删除失败");
        }
        return Result.success();
    }

    /**
     * 取消授权用户角色
     *
     * @param adminRoleMerge 用户和角色关联信息
     * @return 结果
     */
    @Override
    public int deleteAuthUser(AdminRoleMerge adminRoleMerge)
    {
        return adminRoleMergeDao.deleteUserRoleInfo(adminRoleMerge);
    }

    /**
     * 批量取消授权用户角色
     *
     * @param roleId 角色ID
     * @param userIds 需要删除的用户数据ID
     * @return 结果
     */
    public int deleteAuthUsers(Long roleId, String userIds)
    {
        return adminRoleMergeDao.deleteUserRoleInfos(roleId, Convert.toLongArray(userIds));
    }
    // ///////////////////////////////
    // /////        修改      ////////
    // ///////////////////////////////
    /**
     * 修改保存角色信息
     *
     * @param adminRoleDO 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public Object updateAdminRole(AdminRoleDO adminRoleDO){
        if(org.springframework.util.StringUtils.isEmpty(adminRoleDO.getId())){
            return Result.failure("角色信息id不能为空");
        }
        if(this.checkRoleNameUnique(adminRoleDO.getRoleName(),adminRoleDO.getId())){
            return Result.failure("该角色名称已存在");
        }
        if(this.checkRoleKeyUnique(adminRoleDO.getRoleName(),adminRoleDO.getId())){
            return Result.failure("该角色key已存在");
        }
        AdminRole adminRole=new AdminRole();
        adminRole.setId(adminRoleDO.getId());
        adminRole.setRoleName(adminRoleDO.getRoleName());
        adminRole.setRoleKey(adminRoleDO.getRoleKey());
        adminRole.setRemark(adminRoleDO.getRemark());
        adminRole.setStatus(adminRoleDO.getStatus());
        adminRole.setSortOrder(adminRoleDO.getSortOrder());
        int totalCount = adminRoleDao.updateAdminRole(adminRole);
        if(totalCount == 0){
            Result.failure("更新失败");
        }
        List<AdminRoleMenuMerge> list = new ArrayList<AdminRoleMenuMerge>();
        //清除当前角色所有关联
        adminRoleMenuMergeDao.deleteRoleMenuByRoleId(adminRoleDO.getId());
        //重新添加关联信息
        Arrays.asList(adminRoleDO.getTreeId().split(",")).forEach(
                menuId-> {
                    AdminRoleMenuMerge rm = new AdminRoleMenuMerge();
                    rm.setId(SnowFlakeUtils.nextId());
                    rm.setRoleId(adminRoleDO.getId());
                    rm.setMenuId(Long.parseLong(menuId));
                    list.add(rm);
                });
        adminRoleMenuMergeDao.batchRoleMenu(list);
        return Result.success();
    }

    /**
     * 角色状态修改
     *
     * @param adminRole 角色信息
     * @return 结果
     */
    @Override
    public int changeStatus(AdminRole adminRole)
    {
        return adminRoleDao.updateAdminRole(adminRole);
    }


    // ///////////////////////////////
    // /////        查詢      ////////
    // ///////////////////////////////

    /**
     * 查询角色id和菜单id是否已关联
     *
     * @param roleId
     *        角色id
     * @param menuId
     *        菜单id
     * @return
     */
    public boolean checkRoleMenuMerge(Long roleId,Long menuId) {
        int totalCount = adminRoleMenuMergeDao.checkRoleMenuMerge(roleId,menuId);
        return totalCount > 0 ? true : false;
    }

    /**
     * 根据条件分页查询角色数据
     *
     * @param role 角色信息
     * @return 角色数据集合信息
     *
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @return
     */
    public Object selectRoleListPager(AdminRole role, Integer page, Integer limit, String sort, String order) {
        //javabean 映射工具
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        MapperFacade mapper = mapperFactory.getMapperFacade();

        StringBuffer whereStr = new StringBuffer(" 1 = 1");
        if (!org.springframework.util.StringUtils.isEmpty(role.getRoleName())) {
            whereStr.append(" and role_name like concat('%',#{entity.roleName},'%')");
        }
        if (!org.springframework.util.StringUtils.isEmpty(role.getStatus())) {
            whereStr.append(" and status = #{entity.status}");
        }
        if (!org.springframework.util.StringUtils.isEmpty(role.getRoleKey())) {
            whereStr.append(" and role_key like concat('%',#{entity.roleKey},'%')");
        }
        whereStr.append(" and deleted = 0");

        Pager<AdminRole> pager = new Pager(page, limit);
        //排序设置
        if (!org.springframework.util.StringUtils.isEmpty(sort)) {
            Boolean rank = "asc".equals(order) ? true : false;
            pager.addOrderProperty(sort, rank,true);
        }
        //使用limit进行查询翻页
        pager.addLimitProperty(true);
        //查询条件
        AdminRole entity = new AdminRole();
        entity.setRoleName(role.getRoleName());
        entity.setStatus(role.getStatus());
        entity.setRoleKey(role.getRoleKey());
        pager.setEntity(entity);
        pager.setWhereStr(whereStr.toString());
        return LayResult.success(0, "true", adminRoleDao.queryTotal(pager), mapper.mapAsList(adminRoleDao.queryList(pager), AdminRoleVO.class));
    }

    /**
     * 根据用户ID查询角色
     *
     * @param userId 用户ID
     * @return 角色id列表
     */
    @Override
    public String selectUserRolesByUserId(Long userId){
        return adminRoleDao.selectUserRolesByUserId(userId);
    }

    /**
     * 根据用户ID查询权限
     * 
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRoleKeys(Long userId)
    {
        if(org.springframework.util.StringUtils.isEmpty(userId)){
            return null;
        }
        List<AdminRole> perms = adminRoleDao.selectRolesByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (AdminRole perm : perms)
        {
            if (StringUtils.isNotNull(perm))
            {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

/*    *//**
     * 根据用户ID查询角色
     * 
     * @param userId 用户ID
     * @return 角色列表
     *//*
    @Override
    public List<Role> selectRolesByUserId(Long userId)
    {
        List<Role> userRoles = roleDao.selectRolesByUserId(userId);
        List<Role> roles = selectRoleAll();
        for (Role role : roles)
        {
            for (Role userRole : userRoles)
            {
                if (role.getRoleId().longValue() == userRole.getRoleId().longValue())
                {
                    role.setFlag(true);
                    break;
                }
            }
        }
        return roles;
    }*/


     /**
     * 查询所有角色
     * 
     * @return 角色列表
     */

    @Override
    public List<AdminRole> selectRoleAll() {
        StringBuffer whereStr = new StringBuffer(" 1 = 1");
        whereStr.append(" and deleted = 0");
        Pager<AdminRole> pager = new Pager();
        //排序设置
        pager.addOrderProperty(null, false,false);
        //使用limit进行查询翻页
        pager.addLimitProperty(true);
        pager.setWhereStr(whereStr.toString());
        return adminRoleDao.queryList(pager);
    }

    /**
     * 通过角色ID查询角色
     * 
     * @param id 角色ID
     * @return 角色对象信息
     */
    public AdminRole findById(Long id)
    {
        return adminRoleDao.findById(id);
    }


    /**
     * 校验角色名称是否唯一
     *
     * @param roleName
     *         校验角色名称
     * @param id 需要排除的角色id
     * @return
     */
    public boolean checkRoleNameUnique(String roleName,Long id) {
        AdminRole role = adminRoleDao.checkRoleNameUnique(roleName,id);
        return role != null ? true : false;
    }

    /**
     * 校验角色权限是否唯一
     *
     * @param roleKey 角色权限key
     * @param id 需要排除的角色id
     * @return 结果
     */
    public boolean checkRoleKeyUnique(String roleKey,Long id)
    {
        AdminRole role = adminRoleDao.checkRoleKeyUnique(roleKey,id);
        return role != null ? true : false;
    }

    /**
     * 通过角色ID查询角色使用数量
     * 
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public int countUserRoleByRoleId(Long roleId)
    {
        return adminRoleMergeDao.countUserRoleByRoleId(roleId);
    }

}
